<?php

namespace App\Repository\Service;

use App\Models\Admin\AdminUsers;
use App\Models\Service\ServiceCallModel;
use App\Models\Service\ServiceCallTaskModel;
use App\Models\Service\ServiceSendMsgModel;
use App\Repository\BaseRepository;
use App\Repository\Orders\HandlesRepository;
use App\Repository\Orders\OrdersUserRepository;
use Illuminate\Support\Facades\Cache;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class ServiceCallRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new ServiceCallModel();
        $this->log = new Logger('ServiceCall');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ServiceCall.log'), 5, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    //列表
    public function index($params, $page = 1, $limit = 10)
    {
        $where = [];
        $where['gt']['status'] = 0;
        if (isset($params['orders_id'])) {
            $where['eq']['orders_id'] = $params['orders_id'];
        }
        $rows = [];
        $total = 0;
        if (!isset($params['getFlag'])) {
            if ($page <= 1) {
                $total = $this->model->searchWhere($where)->count('id');
            }
        }
        $rows = $this->model->searchWhere($where)->orderByDesc('id')->page($page, $limit)->get();
//        echo $this->getLastSql();
        return $this->returnMsg(200, '查询成功', $rows, $total);
    }


//记录
    public function ordersLogs($ordersId)
    {
        $where = [
            'orders_id' => $ordersId
        ];
        $rows = $this->model->where($where)->orderByDesc('id')->get()->toArray();
        return $this->returnMsg(200, '查询成功', $rows);
    }

    public function savePushCallResult($postData)
    {
        $usersId = $postData['user']['id'];
        if (empty($postData['user'])) {
            return $this->returnMsg(2, '帐号信息异常');
        }
//        推送的是录音
        if (isset($postData['record'])) {
            $this->log->info("录音记录:" . json_encode($postData));
            if (empty($postData['callId'])) {
                return $this->returnMsg(2, '外呼ID不能为空');
            }
            if (empty($postData['record'])) {
                return $this->returnMsg(2, '上传的录音为空');
            }
            $callId = trim($postData['callId']);
            $oldRow = $this->model->where(['call_id' => $callId])->select(['id', 'record'])->first();
            if (!empty($oldRow)) {
//                一般来说录音的推送要晚于内容推送,所以找到这个订单后可以更新录音
                if (empty($oldRow['record'])) {
                    $this->model->where(['id' => $oldRow['id']])->update(['record' => $postData['record']]);
                }
            } else {
//                缓存起来
                Cache::put($callId, $postData['record'], 3600);
            }
        } else if ($postData['type'] === 'calllog') {
            $this->log->info('通话记录:' . json_encode($postData));
//            推送的是通话记录,它是一个数组格式
            $content = $postData['content'];
            $dataArr = [];
//            https://www.kancloud.cn/xulijie/websocket_document/2165467
            foreach ($content as $key => $val) {
//                前端的数据还原成数组
                parse_str(rawurldecode($val['extraparam']), $dataArr);
                if (empty($dataArr['orders_id'])) {
                    continue;
                }
                $callId = trim($val['callId']);
//                通话ID,唯一标识
                if (empty($callId)) {
                    continue;
                }
                $service_call_id = $dataArr['service_call_id'] ?? 0;
                $record = '';
                if (Cache::has($callId)) {
                    $record = Cache::get($callId);
                    Cache::forget($callId);
                }
                $upData = [
                    'call_id' => $callId,
//                    'users_id' => $usersId,
                    'nickname' => $postData['user']['nick_name'],
                    'call_task_id' => $dataArr['task_id'] ?? 0,
                    'orders_id' => $dataArr['orders_id'] ?? 0,
                    'ordersno' => $dataArr['ordersno'] ?? '',
                    'orders_status' => $dataArr['orders_status'] ?? 0,
                    'service_user_id' => $dataArr['service_user_id'] ?? 0,
                    'md5sum' => md5($dataArr['md5str']),
                    'ccid' => $val['ccid'] ?? '',
                    'device' => $val['IMEI'] ?? '',
                    'phone' => $val['callee'] ?? '',
                    'link_type' => $val['callFlag'] == 1 ? 1 : 2,
                    'talk_number' => $val['caller'] ?? '',
                    'talk_type' => $val['callDirection'] ?? 0,
                    'created_at' => date('Y-m-d H:i:s', strtotime($val['startTime'])),
                    'overed_at' => date('Y-m-d H:i:s', strtotime($val['endTime'])),
                    'talk_time' => $val['talktime'] ?? 0
                ];
                if (!empty($record)) {
                    $upData['record'] = $record;
                }
                $where = ['md5sum' => $upData['md5sum']];
                //采用了指定任务id方式
                if ($service_call_id > 0) {
                    $where = ['id' => $service_call_id];
                }
                $this->model->where($where)->update($upData);
            }
            return $this->returnMsg(200, '通话记录保存成功');
        }
        return $this->returnMsg(10, '内容不明确');
    }

//    保存外呼结果,这是标识结果,会先于推送的
    public function saveCallResult($params)
    {
//        $serviceId = $params['user']['id'];
        if (empty($params['user'])) {
            return $this->returnMsg(2, '帐号信息异常');
        }
        if (empty($params['orders_id'])) {
            return $this->returnMsg(2, '订单信息异常');
        }
        $md5sum = md5($params['md5str']);
        $upData = [
            'status' => intval($params['status'])
        ];
        if (!empty($params['remark'])) {
            $upData['remark'] = $params['remark'];
        }
        if (!empty($params['label_id'])) {
            $upData['label_id'] = intval($params['label_id']);
        }
        if (!empty($params['label_name'])) {
            $upData['label_name'] = $params['label_name'];
        }
        if (!empty($params['tagging'])) {
            $upData['tagging'] = intval($params['tagging']);
        }
        if (!empty($params['forbids'])) {
            if (is_string($params['forbids'])) {
                $upData['forbids'] = explode(',', $params['forbids']);
            } else {
                $upData['forbids'] = $params['forbids'];
            }
        }
        $where = ['md5sum' => $md5sum];
        if ($upData['status'] == 4) {
//            这个操作下是没有先保存的md5sum的,不能以md5sum来作条件
            $where = [
                'call_task_id' => $params['call_task_id'],
                'orders_id' => $params['orders_id'],
                'status' => 0
            ];
        }
//        采用了指定任务id方式
        if ($params['service_call_id'] > 0) {
            $where = ['id' => $params['service_call_id']];
        }
        $this->model->where($where)->update($upData);
        //任务表更新
        $ModelCallTask = new ServiceCallTaskModel();
        if (isset($params['call_task_id']) && $params['call_task_id'] > 0) {
//            标识任务通话情况
            $where = ['id' => $params['call_task_id']];
            $row = $ModelCallTask->where($where)->select(['nums', 'overs', 'flag_ok', 'flag_no'])->first();
            $upCallTaskData = [];
            $upCallTaskData['overs'] = $row->overs + 1;
            if ($upData['status'] == 1) {
//                标记未接听
                $upCallTaskData['flag_no'] = $row->flag_no + 1;
            } else if ($upData['status'] == 2 || $upData['status'] == 3) {
//                标记未接听
                $upCallTaskData['flag_ok'] = $row->flag_ok + 1;
            }
//               打完了
            if ($upCallTaskData['overs'] >= $row['nums']) {
                $upCallTaskData['status'] = 2;
            }
            $ModelCallTask->where($where)->update($upCallTaskData);
        }
//        修改了小旗与定单同步
        $params['ordersId'] = $params['orders_id'];
        $params['ordersNo'] = $params['ordersno'];
        $Repository = new OrdersUserRepository();
        $Repository->editTagging($params);
        $upOrdersData = [];
        if (!empty($params['forbids'])) {
            $forbidChangeStatus = config('card.forbidChangeStatus');
            foreach ($params['forbids'] as $k => $v) {
                $upOrdersData[$forbidChangeStatus[$v]['field']] = 1;
            }
        }
//        回收时的订单状态更改
        if ($params['status'] == 3) {
            $upOrdersData['status'] = 70;
        }
        if (!empty($upOrdersData)) {
            $OrdersRepository = new HandlesRepository();
            $OrdersRepository->changeOrdersFields($params['user']['id'], $params['orders_id'], $upOrdersData);
        }
        return $this->returnMsg(200, '通话信息保存完毕');
    }

    public function callDetail($params)
    {
        if (!isset($params['users_id']) || $params['users_id'] <= 0) {
            return $this->returnMsg(2, '请指定外呼人员', []);
        }
        $page = $params['pageNum'] ?? 1;
        $limit = $params['pageSize'] ?? 10;
        $where = [];
        if (isset($params['dateRange']) && is_array($params['dateRange'])) {
            $where['between']['a.created_at'] = $params['dateRange'];
        }
        $where['eq']['a.users_id'] = $params['users_id'];
        $aField = ["orders_id", "users_id", "nickname", "status", "created_at",
            "overed_at", "talk_type", "talk_number", "link_type",
            "ordersno", "talk_time", "call_task_id", "service_user_id"];
        $fields = ['b.title'];
        foreach ($aField as $field) {
            $fields[] = 'a.' . $field;
        }
        $rows = [];
        $ModeCallTask = new ServiceCallTaskModel();
        $total = $this->model->from($this->model->getTable(), 'a')->searchWhere($where)->count('a.id');
        foreach ($this->model->from($this->model->getTable(), 'a')
                     ->leftJoin($ModeCallTask->getTable() . ' AS b', 'a.call_task_id', '=', 'b.id')
                     ->searchWhere($where)
                     ->select($fields)
                     ->page($page, $limit)
                     ->cursor() as $row) {
            $rows[] = $row;
        }
        return $this->returnMsg(200, '获取成功', $rows, $total);
    }

    //人员报表
    public function peopleReport($params)
    {
        $where = [];
        if (isset($params['dateRange']) && is_array($params['dateRange'])) {
            $where['between']['created_at'] = $params['dateRange'];
        }
        if (isset($params['service_user_id']) && $params['service_user_id'] > 0) {
            $where['eq']['service_user_id'] = $params['service_user_id'];
        }
        $aField = ["orders_id", "users_id", "nickname", "status", "created_at",
            "overed_at", "talk_type", "talk_number", "link_type",
            "ordersno", "talk_time", "call_task_id", "service_user_id"];
        $fields = ['b.nick_name AS service_name'];
        foreach ($aField as $field) {
            $fields[] = 'a.' . $field;
        }
        $rows = [];
        $ModelUsers = new AdminUsers();
        $level = $params['level'] ?? 0;
//        具体外呼人员的外呼记录
        if ($level >= 2) {
            return $this->callDetail($params);
        }
        foreach ($this->model->from($this->model->getTable(), 'a')
                     ->leftJoin($ModelUsers->getTable() . ' AS b', 'a.service_user_id', '=', 'b.id')
                     ->searchWhere($where)
                     ->select($fields)
                     ->cursor() as $row) {
            if ($level == 0) {
//                第一层是归属人数据
                $keyId = $row['service_user_id'];
                $rows[$keyId]['users_id'] = $row['service_user_id'];
                // 添加子表格数据
                $rows[$keyId]['hasChildren'] = true;
                $rows[$keyId]['children'] = [];
//                外呼人员,显示总数
                if (isset($rows[$keyId]['nickname'])) {
                    $rows[$keyId]['nickname'] += 1;
                } else {
                    $rows[$keyId]['nickname'] = 1;
                }
                $rows[$keyId]['service_name'] = $row['service_name'];
            } else {
//                展开时显示的是具体外呼人员的数据,由于可能会与上一层的keyid重复,所以要区分开来加level
                $keyId = $row['users_id'] . $level;
                $rows[$keyId]['users_id'] = $row['users_id'];
                $rows[$keyId]['hasChildren'] = false;
                $rows[$keyId]['children'] = [];
//                外呼人员
                $rows[$keyId]['nickname'] = $row['nickname'];
                $rows[$keyId]['service_name'] = '';
            }
//            当前内容层级
            $rows[$keyId]['level'] = $level;

//            拨打数量
            if (isset($rows[$keyId]['total_talk_num'])) {
                $rows[$keyId]['total_talk_num'] += 1;
            } else {
                $rows[$keyId]['total_talk_num'] = 1;
            }
//            转数组的时候保留值
            $rows[$keyId]['keyId'] = $keyId;
//拨通数量
            if (isset($rows[$keyId]['total_talk_ok'])) {
                $rows[$keyId]['total_talk_ok'] += $row['link_type'] == 1 ? 1 : 0;
            } else {
                $rows[$keyId]['total_talk_ok'] = $row['link_type'] == 1 ? 1 : 0;
            }
//            拨通率
            $rows[$keyId]['total_talk_rate'] = 0;
            if ($rows[$keyId]['total_talk_ok'] > 0) {
                $rows[$keyId]['total_talk_rate'] = round(($rows[$keyId]['total_talk_ok'] / $rows[$keyId]['total_talk_num']) * 100, 1);
            }
//            平均拨打成本,已经发生的拨打成本，算法：拨打次数/拨打数量
            $rows[$keyId]['total_talk_cost'] = 0;
            if ($rows[$keyId]['total_talk_num'] > 0) {
                $rows[$keyId]['total_talk_cost'] = round(($rows[$keyId]['total_talk_ok'] / $rows[$keyId]['total_talk_num']) * 100, 1);
            }

//            短信发送数量
            $rows[$keyId]['total_send_msg_num'] = 0;
        }
//        短信数据
        $ModelSendMsg = new ServiceSendMsgModel();
        foreach ($ModelSendMsg->searchWhere($where)
                     ->select(['service_user_id', 'users_id', 'status'])
                     ->cursor() as $row) {
            if ($level == 0) {
//                第一层是归属人数据
                $keyId = $row['service_user_id'];
            } else {
//                展开时显示的是具体外呼人员的数据
                $keyId = $row['users_id'];
            }
            if (isset($rows[$keyId]['total_send_msg_num'])) {
                $rows[$keyId]['total_send_msg_num'] += 1;
            }
        }
        return $this->returnMsg(200, '数据已查询', array_values($rows));
    }
}
